import 'dart:io';

import 'package:cloud_medicine/components/above_loading.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/shop_api.dart';
import 'package:cloud_medicine/model/base_user_info.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ErrorCenter extends StatefulWidget {
  ErrorCenter({Key key}) : super(key: key);

  @override
  _ErrorCenterState createState() => _ErrorCenterState();
}

class _ErrorCenterState extends State<ErrorCenter> {
  TextEditingController _editingController;
  bool isManage = user.identify.id == 6; //判断身份是否是管理员
  bool _loading = false;

  List<String> images = [];
  final picker = ImagePicker();
  Future<Null> _init() async {
    setState(() {
      _loading = true;
    });

    if (mounted) {
      setState(() {
        _loading = false;
      });
    }
    return;
  }

  @override
  void initState() {
    _editingController = new TextEditingController();

    _init();
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _editingController.dispose();
  }

  pickImage() {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
              height: 120,
              child: Column(
                children: <Widget>[_item('拍照', true), _item('从相册选择', false)],
              ),
            ));
  }

  _item(String title, bool isTakePhoto) {
    return GestureDetector(
      child: ListTile(
        leading: Icon(isTakePhoto ? Icons.camera_alt : Icons.photo_library),
        title: Text(title),
        onTap: () => getImage(isTakePhoto),
      ),
    );
  }

  Future getImage(bool isTakePhoto) async {
    Navigator.pop(context);
    final pickedFile = await picker.getImage(
        source: isTakePhoto ? ImageSource.camera : ImageSource.gallery);

    showDialog(
        context: context,
        builder: (context) {
          return new AboveLoading();
        });
    await upLoadImage(File(pickedFile.path), (imageUrl) {
      setState(() {
        images.add(imageUrl);
      });
      Navigator.pop(context);
    });
  }

  _imageShow() {
    print(images);
    if (images.length != 0) {
      return images
          .map((e) => Container(
                width: 70,
                height: 70,
                child: Image.network(e),
              ))
          .toList();
    } else {
      return _list;
    }
  }

  Future _reportError() async {
    await reportError_api('$backIP/error', {
      'identity': user.identify.id,
      'word': _editingController.text,
      'picture': images
    });
  }

  List<Widget> _list = [];
  Widget _childLayout() {
    if (_loading) {
      return Center(
        child: Container(
          child: CircularProgressIndicator(),
        ),
      );
    } else {
      if (!isManage) {
        return ListView(
          children: [
            Container(
              padding: EdgeInsets.only(top: 10),
              alignment: Alignment.topCenter,
              child: Text(
                '欢迎向我们提出宝贵的意见~',
                style: TextStyle(color: Colors.grey),
              ),
            ),
            Container(
                padding: EdgeInsets.all(10),
                child: TextField(
                  controller: _editingController,
                  maxLines: 5,
                  keyboardType: TextInputType.text,
                  decoration: InputDecoration(
                      prefixIcon: Icon(Icons.content_copy),
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(15))),
                )),
            Container(
              child: Text(
                '如果方便的话，您可以配些图片~',
                style: TextStyle(color: Colors.grey),
              ),
              alignment: Alignment.topCenter,
            ),
            Container(
                child: Row(children: [
              GestureDetector(
                onTap: pickImage,
                child: Container(
                  margin: EdgeInsets.all(5),
                  width: 70,
                  height: 70,
                  decoration: BoxDecoration(
                      border:
                          Border.all(width: 1, color: Colors.lightBlueAccent)),
                  child: Icon(Icons.add, color: Colors.lightBlueAccent),
                ),
              ),
              Wrap(
                children: _imageShow(),
              ),
            ])),
            Container(
              padding: EdgeInsets.only(left: 10, right: 10),
              child: RaisedButton(
                  color: Colors.blue,
                  child: Text(
                    '提交',
                    style: TextStyle(color: Colors.white),
                  ),
                  onPressed: () {
                    if (_editingController.text.trim() == "" &&
                        images.isEmpty) {
                      openAlertDialog(context, () {}, '您还没有任何反馈哦~');
                    } else {
                      _reportError();
                      openAlertDialog(context, () {
                        Navigator.pop(context);
                      }, "感谢您的反馈~");
                    }
                  }),
            )
          ],
        );
      } else {
        return Container(
            child: (Center(
          child: Text('请去管理员网页后台处理~'),
        )));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('错误中心'),
      ),
      body: _childLayout(),
    );
  }
}
